﻿using Avalonia.Threading;
using AvaloniaDevice.Common.Services;
using AvaloniaDevice.Common.WIFI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Xamarin.Essentials;


namespace AvaloniaAndroidDemo.ViewModels;

public class MainViewModel : ViewModelBase
{
    private readonly IWifiService _wifiService;
    private bool _isWifiEnabled;
    private WifiInfo _connectedWifi;
    private string _statusMessage;
    private bool _isScanning;

    [Reactive]
    public ObservableCollection<WifiInfo> AvailableNetworks { get; set; } = new ObservableCollection<WifiInfo>();

    [Reactive] public bool IsWifiEnabled{ get; set; }

    [Reactive] public WifiInfo ConnectedWifi { get; set; }
    [Reactive] public WifiInfo SelectWifi { get; set; }

    [Reactive] public string StatusMessage { get; set; }
    [Reactive] public string Password { get; set; }

    [Reactive] public bool IsScanning { get; set; }
 

    public MainViewModel()
    {
        _wifiService = App.WifiService;// DependencyService.Get<IWifiService>();

        //ToggleWifiCommand = new RelayCommand(async () => await ToggleWifi());
        //ScanNetworksCommand = new RelayCommand(async () => await ScanNetworks());
        //ConnectToNetworkCommand = new RelayCommand<WifiInfo>(async (wifi) => await ConnectToNetwork(wifi));
        //DisconnectCommand = new RelayCommand<WifiInfo>(async (wifi) => await Disconnect(wifi));

        // 初始化状态
        UpdateWifiStatus();
    }

    public async Task ToggleWifi()
    {
        try
        {
            await _wifiService.SetWifiEnabled(!IsWifiEnabled);
            await Task.Delay(1000);
            UpdateWifiStatus();
        }
        catch (Exception ex)
        {
            StatusMessage = $"操作失败: {ex.Message}";
        }
    }

    public async Task ScanNetworks()
    {
        if (!IsWifiEnabled)
        {
            StatusMessage = "请先开启WiFi";
            return;
        }

        try
        {
            IsScanning = true;
            StatusMessage = "正在扫描WiFi网络...";
            AvailableNetworks.Clear();

            // 检查并请求定位权限（Android 6.0+ 需要）
            var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
                if (status != PermissionStatus.Granted)
                {
                    StatusMessage = "需要定位权限才能扫描WiFi";
                    IsScanning = false;
                    return;
                }
            }

            var networks = await _wifiService.GetAvailableNetworks();
            foreach (var network in networks)
            {
                AvailableNetworks.Add(network);
            }

            StatusMessage = $"找到 {networks.Count} 个WiFi网络";
        }
        catch (Exception ex)
        {
            StatusMessage = $"扫描失败: {ex.Message}";
        }
        finally
        {
            IsScanning = false;
        }
    }

    public async Task ConnectToNetwork( )
    {
        WifiInfo wifi = SelectWifi;
        if (wifi == null) return;

        try
        {
            StatusMessage = $"正在连接到 {wifi.Ssid}...";

            string password = null;
            if (wifi.IsEncrypted)
            {
                // 这里应该显示密码输入对话框
                password = Password; // 实际应用中应从用户输入获取
            }

            bool success = await _wifiService.ConnectToWifi(wifi.Ssid, password);
            if (success)
            {
                StatusMessage = $"已成功连接到 {wifi.Ssid}";
                UpdateWifiStatus();
                await ScanNetworks();
            }
            else
            {
                StatusMessage = $"连接 {wifi.Ssid} 失败";
            }
        }
        catch (Exception ex)
        {
            StatusMessage = $"连接失败: {ex.Message}";
        }
    }

    public async Task Disconnect(WifiInfo wifi)
    {
        if (wifi == null) return;

        try
        {
            StatusMessage = $"正在断开 {wifi.Ssid} 的连接...";
            bool success = await _wifiService.DisconnectFromWifi(wifi.Ssid);

            if (success)
            {
                StatusMessage = $"已断开与 {wifi.Ssid} 的连接";
                UpdateWifiStatus();
                await ScanNetworks();
            }
            else
            {
                StatusMessage = $"断开 {wifi.Ssid} 连接失败";
            }
        }
        catch (Exception ex)
        {
            StatusMessage = $"断开连接失败: {ex.Message}";
        }
    }

    public void UpdateWifiStatus()
    {
        Dispatcher.UIThread.Post(() =>
        {
            IsWifiEnabled = _wifiService.IsWifiEnabled();
            ConnectedWifi = _wifiService.GetConnectedWifi();

            if (ConnectedWifi != null)
            {
                StatusMessage = $"当前连接: {ConnectedWifi.Ssid} (信号强度: {ConnectedWifi.SignalStrength}%)";
            }
            else if (IsWifiEnabled)
            {
                StatusMessage = "WiFi已开启，但未连接到任何网络";
            }
            else
            {
                StatusMessage = "WiFi已关闭";
            }
        });
    }

 
}
